package com.adjaisd.mqtt.service.impl;

import com.adjaisd.mqtt.service.RedisService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    @Override
    public Boolean existKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public Boolean isOverdue(String key) {
        return getExpire(key) <= 0;
    }

    @Override
    public Boolean equalVal(String key, String token) {
        return get(key).equals(token);
    }

    @Override
    public void set(String key, String value, long expire) {
        //更改在redis里面查看key编码问题
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.set(key, value, expire, TimeUnit.MINUTES);//设置key并且设置有效时间
    }

    /*
     * 删除key
     * */
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }


    @Override
    public Boolean update(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.MINUTES);
    }

    /*
     * 查询key
     * */
    public Object get(String key) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        return vo.get(key);
    }
}